﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace ApiDoc
{
    /// <summary>
    /// Extensions for MarkupString.
    /// </summary>
    public static class MarkupStringExtensions_Html
    {
        /// <summary>
        /// Returns a HTML version of <paramref name="innerXml"/> with &lt;paramref&gt; etc. replaced with links to the API from the <paramref name="apiBaseUrl"/> calls.
        /// </summary>
        /// <param name="html"></param>
        /// <param name="innerXml"></param>
        /// <returns></returns>
        public static IHtmlString ToHtml(this MarkupString s, string apiBaseUrl)
        {
            var manager = s.GetManager();
            var member = s.GetOwner();

            string text = manager.CreateDocumentationStringWithLinks(s.ToString(), member, lookupAllWords: true);

            // Swap tags to links based on the base URL.
            var matches = Regex.Matches(text, "<link type=\"([^\"]*)\" cref=\"([^\"]*)\">([^<]*)</link>")
                .Cast<Match>();
            foreach (var match in matches) {
                text = text.Replace(match.Value, String.Format("<a href=\"{3}/{2}/{0}\">{1}</a>", HtmlHelper_ApiDocumentation.UrlFriendlyCref(match.Groups[2].Value), match.Groups[3].Value, match.Groups[1].Value, apiBaseUrl));
            }

            return MvcHtmlString.Create(text);
        }
    }
}
